package com.example.springbooksystem.service;


import com.example.springbooksystem.enums.BookStatusEnum;
import com.example.springbooksystem.mapper.BookMapper;
import com.example.springbooksystem.model.BookInfo;
import com.example.springbooksystem.model.PageRequest;
import com.example.springbooksystem.model.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description：业务逻辑层: 处理具体的业务逻辑。
 * 业务逻辑层根据控制层的要求, 向数据层拿取对应的数据, 将数据进行一定逻辑处理后, 将处理完的数据发送给控制层
 *
 * @author: zxj
 * @date: 2023-11-08
 * @time: 16:47:13
 */
// 将 BookService 交给 Spring进行管理
@Service
@Slf4j
public class BookService {
    @Autowired
    BookMapper bookMapper;

    public PageResult<BookInfo> getBookList(PageRequest pageRequest) {
        int offset = pageRequest.getOffset();
        int pageSize = pageRequest.getPageSize();
        Integer count = bookMapper.count();
        List<BookInfo> bookInfoList = bookMapper.select(offset, pageSize);
        // 处理页面展示 -- 图书的状态: 数字描述 -> 中文描述
        for (BookInfo bookInfo : bookInfoList) {
            //根据status 获取状态的定义
            bookInfo.setStatusCN(BookStatusEnum.getNameByCode
                            (bookInfo.getStatus())
                    .getMessage());
        }

        return new PageResult<>(bookInfoList, count, pageRequest);
    }

    public Integer addBook(BookInfo bookInfo) {
        try {
            return bookMapper.insert(bookInfo);
        } catch (Exception e) {
            log.error("数据库添加图书出错, bookInfo: {}", bookInfo);
            return -1;
        }
    }

    public BookInfo queryById(Integer id) {
        try {
            return bookMapper.selectById(id);
        } catch (Exception e) {
            log.error("数据库查询书籍id失败");
            return null;
        }
    }

    public Integer updateBook(BookInfo bookInfo) {
        try {
            return bookMapper.updateBook(bookInfo);
        } catch (Exception e) {
            log.error("更新图书失败, bookInfo: {}",bookInfo);
            return null;
        }
    }

    public Integer batchDeleteBook(List<Integer> ids) {
        try {
            return bookMapper.batchDeleteBookByIds(ids);
        } catch (Exception e) {
            log.error("数据库删除图书失败, ids: {}",ids);
            return null;
        }

    }
}
